<?php
/**
 *
 * User: konakona http://www.crazyphper.com
 * Date: 13-5-19
 * Time: 下午8:17
 */
class ShopCartAction extends CommonAction {

    public function _initialize() {
        parent::_initialize();
        $address = M( 'Address' )->where( array( 'used' => 1 , 'uid' => $this->uid ) )->find(); //用户的默认收货地址和姓名
        if ( !$address ) {
            $this->error( "请先选择默认收货地址！" , U( 'Member/address_list' ) );
        }
    }

    public function index() {
        if ( $_POST ) {
            if ( $_POST[ 'update' ] ) {
                $this->update();
            } elseif($_POST['submit']){
                $this->assign( 'title' , '请填写订单详细' );
                $this->display( 'make_sure' );
            }
        } else {
            $this->assign( 'title' , '购物车' );
            $shopCart = D( 'ShopCart' )->getMine( $this->uid );
            if ( !$shopCart ) {
                $this->error( "您还没有添加商品到购物车呢！" , U( 'Shop/index' ) );
            }

            $this->assign( 'shop_cart' , $shopCart );
            $this->assign( 'total_price' , D( 'ShopCart' )->getTotalPrice( $shopCart ) );
            //读取4个秒杀商品
            $this->assign('shop_list',D('Shop')->getList(0, 2, 0,4));
            $this->display();
        }
    }

    /**
     * 变更为订单
     * 并清空的购物车
     */
    public function submit() {
        if ( $_POST[ 'way' ] == 'define' ) { //自定发货时间
            $data[ 'delivery_time' ] = $_POST[ 'day' ] + $_POST[ 'time' ];
//            echo ( $data[ 'delivery_time' ] - time() );
            if ( ( $data[ 'delivery_time' ] - time() ) < 1800 ) {
                $this->error( "时间错误，请选择比现在晚30分钟的时间！" );
            }
        }
        $address                 = M( 'Address' )->where( array( 'used' => 1 , 'uid' => $this->uid ) )->find(); //用户的默认收货地址和姓名
        $shopCart                = D( 'ShopCart' )->getMine( $this->uid );
        $data[ 'add_time' ]      = time();
        $data[ 'uid' ]           = $this->uid;
        $data[ 'boss_id' ]       = $this->bossID;
        $data[ 'user_address' ]  = $address[ 'address' ];
        $data[ 'user_realname' ] = $address[ 'name' ];
        $orderID                 = M( 'Order' )->add( $data );

        foreach ( $shopCart as $k => $v ) {
			//修改商品数
			$shop = D('Shop')->find($v['shop_id']);
			if($shop['num'] > 0){	//不是无限商品
				if($shop['num'] - $v['num'] <=0){
					//下架商品
					$where['id'] = $v['shop_id'];
					$map['close_time'] = time();
					$map['type'] = 0;
					D('Shop')->where(array('id'=>$v['shop_id']))->save($map);
				}else{
					//修改商品现有数量
					$where['id'] = $v['shop_id'];
					D('Shop')->data($where)->setDec('num',$v['num']);
				}
			}

            $ids[ ] = $v[ 'id' ];
        }

        $id = implode( ',' , $ids );
        //清空本人的购物车
        $this->curModel->where( "id IN ({$id})" )->setField( array( 'type' => 1 , 'order_id' => $orderID ) );

        //		echo $this->curModel->getlastsql();

        //触发发送动作
        $this->sendOrderMail( $orderID );

        redirect( U( 'ShopCart/success_page' , array( 'id' => $orderID ) ) );

//        		$this->success("您已经预订成功！请等待发货！", U('Member/index'));
    }

	/**
	 * 还原商品属性
	 * 在取消订单时其作用
	 */
	protected function re($orderID){
//		$shopCart = $this->curModel->where(array('order_id'=>$orderID))->find();
//		foreach ( $shopCart as $k => $v ) {
//			//修改商品数
//			$shop = D('Shop')->find($v['shop_id']);
//			if($shop['num'] > 0){	//不是无限商品
//				if($shop['num'] - $v['num'] <=0){
//					//下架商品
//					$where['id'] = $v['shop_id'];
//					$map['close_time'] = time();
//					$map['type'] = 0;
//					D('Shop')->where(array('id'=>$v['shop_id']))->save($map);
//				}else{
//					//修改商品现有数量
//					$where['id'] = $v['shop_id'];
//					D('Shop')->data($where)->setDec('num',$v['num']);
//				}
//			}
//
//			$ids[ ] = $v[ 'id' ];
//		}
	}

    /**
     * 预定成功页面
     * 这个页面有30秒取消对话框
     */
    public function success_page() {
        if ( $_POST['cancelOrder'] ) {
            $this->cancel();
        } else {
            $this->assign( 'order_id' , $this->id );
            $this->assign( 'title' , '提交成功');
            $this->display('success');
        }
    }

    /**
     * 取消订单
     */
    protected function cancel() {
        //检查离下单时间是否相差30秒内
        $one = $this->curModel->where( "(UNIX_TIMESTAMP()-add_time) < 30 AND order_id = " . $this->id )->find();
        if ( !$one ) {
            $this->error( "您已经错过了取消订单的机会！" , U( 'Index/index' ) );
        } else {
            M( 'Order' )->delete($this->id);
			$this->re($this->id);
            //还原购物车
            $this->curModel->where(array('order_id' => $this->id ))->setField( array( 'type' => 0 , 'order_id' => 0 ) );

            //发送取消的邮件通知
            $this->sendCancelOrderMail( $this->id );
            $this->success( "正在返回购物车" , U( 'ShopCart/index' ) );
        }
    }

    /**
     * 添加一个商品
     * 应该有数量、商品ID、单价传递过来
     */
    public function add() {
        //获得商品分类
        $shopCateID = D( 'Shop' )->where( array( 'id' => $this->id ) )->getField( 'cate_id' );
        $map        = array( 'shop_id' => $this->id , 'uid' => $this->uid , 'cate_id' => $shopCateID , 'type' => 0);
        if ( $this->curModel->where( $map )->count() == 0 ) {
            $map[ 'num' ] = 1;
			$map['add_time'] = time();
            $this->curModel->data( $map )->add();
        }else{
			$this->curModel->where($map)->setInc('num',1);
		}
        $this->success( "ok" );
    }

    /**
     * 根据递交数据修改购物车记录
     */
    public function update() {
		$errorShop = array();	//记录数量不足的商品
        foreach ( $_POST[ 'num' ] as $id => $num ) {
            if ( $num == 0 ) continue;
			//检查商品数够不够
			$shopID = $this->curModel->where( array( 'id' => $id ) )->getField('shop_id');
			$map['id'] = $shopID;
			$map['num'] = array('GT',0);
			$shop = D('Shop')->where($map)->find();
			if($shop){
				if($shop['num'] - $num <= 0){
					$errorShop[] = $shop['name'];
					continue;
				}
			}
			$this->curModel->where( array( 'id' => $id ) )->setField( 'num' , $num );
        }

		if(count($errorShop) > 0){
			$this->error("修改成功！但由于".implode("/",$errorShop)."商品的数量不足，修改失败");
		}else{
        	$this->success( "修改成功！" , U( 'ShopCart/index' ) );
		}
    }

}
